package com.github.cyf.junkFile.service;

import com.github.cyf.common.util.RedisUtil;
import com.github.cyf.junkFile.constants.JunkFileConstant;
import com.github.cyf.junkFile.entity.UploadResult;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author chenyifan
 * @create 2024-03-27 21:40
 */
@Service
@RequiredArgsConstructor
public class JunkFileService {

    @Autowired
    private RedisUtil redisUtil;

    public List<UploadResult> uploadFile(MultipartFile[] files) {
        List<UploadResult> resultList = Arrays.stream(files)
                .map(file -> upload(file))
                .collect(Collectors.toList());
        List<String> filePathList = resultList.stream()
                .map(UploadResult::getFilePath)
                .collect(Collectors.toList());
        // 将文件路径保存到 redis
        redisUtil.sSet(JunkFileConstant.UPLOAD_RESOURCES_SET, filePathList.toArray());
        return resultList;
    }

    public void confirm(List<String> filePathList) {
        redisUtil.sSet(JunkFileConstant.SAVE_RESOURCES_SET, filePathList.toArray());
    }

    public Map<String, Object> getResult() {
        Map<String, Object> map = new LinkedHashMap<>();
        Set<Object> uploadSet = redisUtil.sGet(JunkFileConstant.UPLOAD_RESOURCES_SET);
        Set<Object> saveSet = redisUtil.sGet(JunkFileConstant.SAVE_RESOURCES_SET);
        Set<Object> differenceSet = redisUtil.sDifference(JunkFileConstant.UPLOAD_RESOURCES_SET, JunkFileConstant.SAVE_RESOURCES_SET);
        map.put("已经上传的文件", uploadSet);
        map.put("需要保存的文件", saveSet);
        map.put("需要删除的文件", differenceSet);
        return map;
    }

    /**
     * 模拟上传文件
     * @param file
     * @return
     */
    private UploadResult upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(originalFilename);
        // 模拟上传文件到文件服务器后返回一个文件访问路径
        String filePath = "http://localhost:8888/" + UUID.randomUUID() + "." + extension;
        return new UploadResult(originalFilename, filePath);
    }
}
